﻿using RStudio.UnitSingleton;
using System.Collections;
using System.Linq;
using UnityEngine;
using System.Collections.Generic;

/// <summary>
/// 应用程序入口点 - 支持大规模对象操作的性能优化版本
/// </summary>
public class AppFPS : MonoBehaviour
{
    [Header("性能配置")]
    [SerializeField] private int _minCreatePerBatch = 10;
    [SerializeField] private int _maxCreatePerBatch = 200;
    [SerializeField] private float _createInterval = 0.1f;
    [SerializeField] private float _releaseInterval = 0.15f;
    [SerializeField] private bool _useAsyncMode = true; // 使用异步模式避免卡顿

    [Header("调试信息")]
    [SerializeField] private bool _showDebugInfo = true;
    [SerializeField] private int _currentBatchSize = 50;

    // 性能监控
    private float _currentFPS = 60f;
    private int _totalCreated = 0;
    private int _totalReleased = 0;
    private ServicePrimitiveModelLoader2 _loader;

    // FPS 计算变量
    private float _fpsUpdateTimer = 0f;
    private int _frameCount = 0;
    private float _accumulatedFPS = 0f;

    private void Start()
    {
        // 注册服务
        GameService.Instance.Registers(new ServicePrimitiveModelLoader2(), new ServiceAudio());

        _loader = GameService.Instance.GetService<ServicePrimitiveModelLoader2>();

        // 启动协程
        StartCoroutine(ICreateManager());
        StartCoroutine(IReleaseManager());
        StartCoroutine(IPerformanceMonitor());

        Debug.Log("🚀 AppEntry 启动 - 大规模对象池测试开始");
    }

    private void Update()
    {
        UpdateFPS();
    }

    /// <summary>
    /// 创建管理器 - 智能生成对象
    /// </summary>
    private IEnumerator ICreateManager()
    {
        // 等待一帧确保服务初始化完成
        yield return null;

        while (true)
        {
            yield return new WaitForSeconds(_createInterval);

            // 根据性能动态调整批次大小
            _currentBatchSize = CalculateOptimalBatchSize();
            int createCount = Random.Range(_minCreatePerBatch, _maxCreatePerBatch);
            createCount = Mathf.Clamp(createCount, _minCreatePerBatch, _currentBatchSize);

            if (_showDebugInfo)
            {
                Debug.Log($"🎯 创建批次: {createCount}个对象 | FPS: {_currentFPS:F1} | 动态调整: {_currentBatchSize}");
            }

            if (_useAsyncMode)
            {
                // 异步模式 - 不会卡顿
                CreateObjectsAsync(createCount);
            }
            else
            {
                // 同步模式 - 可能卡顿（用于对比测试）
                CreateObjectsSync(createCount);
            }

            _totalCreated += createCount;
        }
    }

    /// <summary>
    /// 释放管理器 - 智能清理对象
    /// </summary>
    private IEnumerator IReleaseManager()
    {
        while (true)
        {
            yield return new WaitForSeconds(_releaseInterval);

            var activeObjects = _loader.DoGetActives();
            if (activeObjects.Count == 0) continue;

            // 根据性能调整释放数量
            int releaseCount = CalculateOptimalReleaseCount(activeObjects.Count);
            releaseCount = Mathf.Min(releaseCount, activeObjects.Count);

            if (releaseCount > 0)
            {
                if (_useAsyncMode)
                {
                    // 异步释放
                    ReleaseObjectsAsync(activeObjects, releaseCount);
                }
                else
                {
                    // 同步释放
                    ReleaseObjectsSync(activeObjects, releaseCount);
                }

                _totalReleased += releaseCount;

                if (_showDebugInfo)
                {
                    Debug.Log($"🗑️ 释放批次: {releaseCount}个对象 | 活跃总数: {activeObjects.Count}");
                }
            }
        }
    }

    /// <summary>
    /// 异步创建对象（推荐 - 无卡顿）
    /// </summary>
    private void CreateObjectsAsync(int count)
    {
        for (int i = 0; i < count; i++)
        {
            Vector3 position = new Vector3(
                Random.Range(-50f, 50f),
                Random.Range(0f, 10f),
                Random.Range(-50f, 50f)
            );

            PrimitiveType primitiveType = GetRandomPrimitiveType();

            // 使用异步API
            _loader.DoCreateAsync(primitiveType, position, Vector3.one, null, OnObjectCreated);
        }
    }

    /// <summary>
    /// 同步创建对象（可能卡顿）
    /// </summary>
    private void CreateObjectsSync(int count)
    {
        var positions = Enumerable.Range(0, count)
            .Select(i => new Vector3(
                Random.Range(-50f, 50f),
                Random.Range(0f, 10f),
                Random.Range(-50f, 50f)
            ))
            .ToArray();

        PrimitiveType primitiveType = GetRandomPrimitiveType();

        // 使用同步API
        _loader.DoCreate(primitiveType, positions, Vector3.one, null);
    }

    /// <summary>
    /// 异步释放对象
    /// </summary>
    private void ReleaseObjectsAsync(List<GameObject> activeObjects, int count)
    {
        for (int i = 0; i < count; i++)
        {
            if (i < activeObjects.Count)
            {
                int randomIndex = Random.Range(0, activeObjects.Count);
                var objToRelease = activeObjects[randomIndex];

                if (objToRelease != null)
                {
                    _loader.DoUnloadAsync(objToRelease);
                }
            }
        }
    }

    /// <summary>
    /// 同步释放对象
    /// </summary>
    private void ReleaseObjectsSync(List<GameObject> activeObjects, int count)
    {
        var objectsToRelease = activeObjects
            .OrderBy(x => Random.value)
            .Take(count)
            .ToList();

        foreach (var obj in objectsToRelease)
        {
            if (obj != null)
            {
                _loader.DoUnload(obj);
            }
        }
    }

    /// <summary>
    /// 对象创建完成回调
    /// </summary>
    private void OnObjectCreated(GameObject createdObject)
    {
        // 可以在这里添加对象创建后的额外逻辑
        if (_showDebugInfo && _totalCreated % 100 == 0)
        {
            Debug.Log($"✅ 对象创建回调: {createdObject.name} at {createdObject.transform.position}");
        }
    }

    /// <summary>
    /// 性能监控协程
    /// </summary>
    private IEnumerator IPerformanceMonitor()
    {
        while (true)
        {
            yield return new WaitForSeconds(1f); // 每秒更新一次

            var activeObjects = _loader.DoGetActives();
            Debug.Log($"📊 性能统计 | FPS: {_currentFPS:F1} | 活跃对象: {activeObjects.Count} | 总计创建: {_totalCreated} | 总计释放: {_totalReleased}");

            // 性能警告
            if (_currentFPS < 30f)
            {
                Debug.LogWarning($"⚠️ 低帧率警告: {_currentFPS:F1} FPS - 考虑减少批次大小");
            }

            if (activeObjects.Count > 1000)
            {
                Debug.LogWarning($"⚠️ 高内存警告: {activeObjects.Count} 个活跃对象");
            }
        }
    }

    /// <summary>
    /// 更新FPS计算
    /// </summary>
    private void UpdateFPS()
    {
        _fpsUpdateTimer += Time.deltaTime;
        _frameCount++;
        _accumulatedFPS += 1f / Time.deltaTime;

        if (_fpsUpdateTimer >= 0.5f) // 每0.5秒更新一次FPS
        {
            _currentFPS = _accumulatedFPS / _frameCount;
            _fpsUpdateTimer = 0f;
            _frameCount = 0;
            _accumulatedFPS = 0f;
        }
    }

    /// <summary>
    /// 计算最优批次大小
    /// </summary>
    private int CalculateOptimalBatchSize()
    {
        float performanceFactor = _currentFPS / 60f; // 基于60FPS为标准

        if (_currentFPS > 50f)
            return _maxCreatePerBatch;
        else if (_currentFPS > 30f)
            return Mathf.RoundToInt(_maxCreatePerBatch * 0.7f);
        else if (_currentFPS > 20f)
            return Mathf.RoundToInt(_maxCreatePerBatch * 0.4f);
        else
            return _minCreatePerBatch; // 低帧率时使用最小值
    }

    /// <summary>
    /// 计算最优释放数量
    /// </summary>
    private int CalculateOptimalReleaseCount(int activeCount)
    {
        if (activeCount < 100) return 0; // 对象太少时不释放

        float releaseRatio = _currentFPS > 30f ? 0.2f : 0.4f; // 低帧率时加快释放
        return Mathf.RoundToInt(activeCount * releaseRatio);
    }

    /// <summary>
    /// 获取随机基本几何体类型
    /// </summary>
    private PrimitiveType GetRandomPrimitiveType()
    {
        PrimitiveType[] types = {
            PrimitiveType.Cube,
            PrimitiveType.Sphere,
            PrimitiveType.Cylinder,
            PrimitiveType.Capsule
        };
        return types[Random.Range(0, types.Length)];
    }

    /// <summary>
    /// 切换异步/同步模式
    /// </summary>
    public void ToggleAsyncMode(bool useAsync)
    {
        _useAsyncMode = useAsync;
        Debug.Log($"🔄 切换到 {(useAsync ? "异步" : "同步")}模式");
    }

    /// <summary>
    /// 紧急清理所有对象
    /// </summary>
    public void EmergencyCleanup()
    {
        Debug.Log("🚨 紧急清理所有对象");
        _loader.DoUnload();
        _totalCreated = 0;
        _totalReleased = 0;
    }

    /// <summary>
    /// 调整创建间隔
    /// </summary>
    public void SetCreateInterval(float interval)
    {
        _createInterval = Mathf.Clamp(interval, 0.05f, 1f);
        Debug.Log($"⏱️ 创建间隔调整为: {_createInterval:F2}秒");
    }

    private void OnGUI()
    {
        if (!_showDebugInfo) return;

        GUIStyle style = new GUIStyle();
        style.fontSize = 20;
        style.normal.textColor = _currentFPS > 30f ? Color.green :
                                _currentFPS > 20f ? Color.yellow : Color.red;

        int activeCount = _loader?.DoGetActives()?.Count ?? 0;

        GUI.Label(new Rect(10, 10, 400, 30), $"FPS: {_currentFPS:F1}", style);
        GUI.Label(new Rect(10, 40, 400, 30), $"活跃对象: {activeCount}");
        GUI.Label(new Rect(10, 70, 500, 30), $"总计创建/释放: {_totalCreated} / {_totalReleased}");
        GUI.Label(new Rect(10, 100, 400, 30), $"模式: {(_useAsyncMode ? "异步" : "同步")}");
        GUI.Label(new Rect(10, 130, 400, 30), $"批次大小: {_currentBatchSize}");

        // 性能状态指示器
        string status = _currentFPS > 50f ? "✅ 优秀" :
                       _currentFPS > 30f ? "⚠️ 良好" : "❌ 较差";
        GUI.Label(new Rect(10, 160, 400, 30), $"性能: {status}");
    }

    private void OnDestroy()
    {
        // 清理资源
        if (_loader != null)
        {
            _loader.DoUnload();
        }
        Debug.Log("🔚 AppEntry 销毁 - 资源清理完成");
    }
}